package easymall.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import easymall.dao.CartDao;
import easymall.dao.OrderDao;
import easymall.dao.OrderItemDao;
import easymall.po.Order;
import easymall.po.OrderItem;
import easymall.pojo.MyCart;
import easymall.pojo.MyPage;

@Service("orderService")
public class OrderServiceImpl implements OrderService{
	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private CartDao cartDao;
	@Autowired
	private OrderItemDao orderItemDao;

	@Override
	public void addOrder(String cartIds, Order order) {
		String[] arrCartIds = cartIds.split(",");
		Double sum = 0.0;
		for(String cartID : arrCartIds) {
			Integer cid = Integer.parseInt(cartID);
			MyCart mycart = cartDao.findByCartID(cid);
			String pid = mycart.getPid();
			int buynum = mycart.getNum();
			Double price = mycart.getPrice();
			sum += buynum * price;
			OrderItem orderItem = new OrderItem();
			orderItem.setOrder_id(order.getId());
			orderItem.setProduct_id(pid);
			orderItem.setBuynum(buynum);
			orderItemDao.addOrderItem(orderItem);
			cartDao.delCart(cid);  //不删除
		}
		order.setMoney(sum);
		orderDao.addOrder(order);
	}
	
	//根据用户id或取其所有订单
	@Override
	public List<Order> findOrderByUserId(Integer user_id) {
		return orderDao.findOrderByUserId(user_id);
	}
	
	//根据订单id获取对应的商品
	@Override
	public List<OrderItem> getOrderItemsByOrderId(String order_id) {
		return orderItemDao.getOrderItemsByOrderId(order_id);
	}

	@Override
	public void delOrder(String id) {
		orderItemDao.delOrderItem(id);
		orderDao.delOrder(id);
	}

	@Override
	public void payOrder(String id) {
		orderDao.payOrder(id);
	}

	@Override
	public void confirmOrder(String id) {
		orderDao.confirmOrder(id);
		
	}
	
	
	//根据页面号获取订单
	@Override
	public List<Order> getOrdersByPage(Integer page) {
		MyPage mypage = new MyPage(page);
		return orderDao.getOrdersByPage(mypage);
	}

	@Override
	public int totalPage() {
		return (orderDao.getOrdersCount()-1)/MyPage.size + 1;
	}

	@Override
	public Order getOrderById(String id) {
		return orderDao.getOrderById(id);
	}

	//发货
	@Override
	public void sendOrder(Order order) {
		orderDao.sendOrder(order);
		
	}

	@Override
	public List<Order> findAllOrders() {
		// TODO Auto-generated method stub
		return orderDao.findAllOrders();
	}

}
